package com.app.studentActivity;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.app.R;
import com.app.bean.NoticeBean;
import com.app.bean.ShiwuBean;
import com.app.bean.UserBean;
import com.app.util.DBHelper1;
import com.app.util.DBHelper3;
import com.app.util.DateUtil;
import com.app.util.Utils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.bumptech.glide.Glide;

public class ShiwuAdd extends AppCompatActivity {

    private EditText name, content;
    private Button add;
    private ImageView iv_pic;
    private Switch sw;
    private byte[] bytes;
    private String status;
    private ShiwuBean bean;
    private Toolbar toolbar;
    private UserBean userBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shiwu_add);
        initView();
        add.setOnClickListener(v -> {
            //判断上一个界面是否传递数据进来，传递了就编辑，反之就添加
            if (ObjectUtils.isNotEmpty(bean)) {
                editData();
            } else {
                addData();
            }
        });
        //图片控件的点击事件，点击后打开手机的相册进行图片浏览选择
        iv_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                //启动activity，并且要获取结果
                startActivityForResult(intent, 2);

            }
        });
        String user = SPStaticUtils.getString("user");
        userBean = GsonUtils.fromJson(user, UserBean.class);
        //从上个界面获取传递过来的数据
        Integer id = (Integer) getIntent().getSerializableExtra("bean");
        if(ObjectUtils.isNotEmpty(id)){
            String string = SPStaticUtils.getString(id + "");
            bean=GsonUtils.fromJson(string,ShiwuBean.class);
            SPStaticUtils.remove(id + "");
        }

        if (ObjectUtils.isNotEmpty(bean)) {
            ((TextView) toolbar.getChildAt(1)).setText("修改失物招领");
            name.setText(bean.getTitle());
            content.setText(bean.getContent());
//        imageView.setImageResource(bean.getImage());
            Glide.with(this).load(bean.getPic()).into(iv_pic);
            bytes = bean.getPic();
            status = bean.getStatus();
            sw.setVisibility(View.VISIBLE);
            sw.setChecked(bean.getStatus().equals("1"));
        } else {
            ((TextView) toolbar.getChildAt(1)).setText("发布失物招领");
            status="0";
            sw.setVisibility(View.GONE);
        }
        if (ObjectUtils.isEmpty(bytes)) {
            bytes = ImageUtils.bitmap2Bytes(Utils.getIconBitmap(this, R.mipmap.ic_launcher));
        }
    }

    //往数据库插入一条notice
    private void addData() {

        DBHelper3 dbHelper1 = new DBHelper3(this);
        SQLiteDatabase db = dbHelper1.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title", name.getText().toString());
        values.put("content", content.getText().toString());
        values.put("date", DateUtil.getDate());
        values.put("pic", bytes);
        values.put("status", status);
        values.put("username", userBean.getUsername());
        values.put("userid", userBean.getUser_id());
        LogUtils.d("adddd"+GsonUtils.toJson(values));
        long insertResult = db.insert("shiwu", null, values);
        if (insertResult != -1) {
            //修改成功，关闭当前界面
            Toast.makeText(this, "发布成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "发布失败", Toast.LENGTH_SHORT).show();
        }
        db.close();
    }

    private void editData() {
        DBHelper3 dbHelper1 = new DBHelper3(this);
        SQLiteDatabase db = dbHelper1.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title", name.getText().toString());
        values.put("content", content.getText().toString());
        values.put("date", DateUtil.getDate());
        values.put("pic", bytes);
        boolean checked = sw.isChecked();
        values.put("status", checked?"1":"0");
        values.put("username", bean.getUsername());
        values.put("userid", bean.getUserid());
        String selection = "id=?";
        String[] selectionArgs = {String.valueOf(bean.getId())};
        long insertResult = db.update("shiwu", values, selection, selectionArgs);
        if (insertResult != -1) {
            //插入成功，关闭当前界面
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            bean.setTitle((String) values.get("title"));
            bean.setContent((String) values.get("content"));
            bean.setTime((String) values.get("date"));
            bean.setStatus((String) values.get("status"));
            bean.setPic(bytes);
            intent.putExtra("bean",bean.getId());
            SPStaticUtils.put( bean.getId()+"", GsonUtils.toJson(bean));
            setResult(RESULT_OK,intent);
            finish();
        } else {
            Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
        }
        db.close();
    }

    private void initView() {
        toolbar = findViewById(R.id.toolbar);
        toolbar.getChildAt(0).setVisibility(View.INVISIBLE);

        name = findViewById(R.id.name);
        content = findViewById(R.id.content);
        add = findViewById(R.id.add);
        iv_pic = findViewById(R.id.iv_pic);
        sw = findViewById(R.id.sw);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            if (data != null) {
                //从返回回来的数据里获取图片url,并打开一个输入流，并图片流转换成bitmap
                //使用ImageUtils把bitmap图片转换成byte数组
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                    bytes = ImageUtils.bitmap2Bytes(bitmap);
                    Glide.with(this).load(bytes).into(iv_pic);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}